﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Collections.Specialized;
using System.IO;
using System.Web;

namespace TrainingsApp.Helper {
    public class MailHelper {

        public static bool Send(MailAddress to, NameValueCollection dict, string subject = "邮件标题", string templatePath = "/template/mail/default.html") {
            try {
                string htmltemplate = HttpContext.Current.Server.MapPath(templatePath);
                StringBuilder str = null;
                using (FileStream stream = new FileStream(htmltemplate, FileMode.Open, FileAccess.Read)) {
                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
                        str = new StringBuilder(reader.ReadToEnd());
                    }
                }


                if (dict != null) {

                    foreach (string key in dict.Keys) {
                        str.Replace(key, dict[key]);
                    }
                }

                SmtpClient smtp = new SmtpClient();
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

                smtp.Host = "smtp.exmail.qq.com";

                smtp.Credentials = new NetworkCredential("service@yuanyang100.com", "SER987547yang");
                MailMessage mm = new MailMessage();
                mm.Priority = MailPriority.High;
                mm.From = new MailAddress("service@yuanyang100.com", "教育系统", Encoding.GetEncoding(936));

                mm.Sender = new MailAddress("service@yuanyang100.com", "教育系统", Encoding.GetEncoding(936));
                mm.To.Add(to);
                mm.Subject = subject;
                mm.SubjectEncoding = Encoding.UTF8;
                mm.IsBodyHtml = true;
                mm.BodyEncoding = Encoding.UTF8;
                mm.Body = str.ToString();

                smtp.Send(mm);
                return true;
            }
            catch {
                return false;
            }

        }

    }
}
